package com.zcy.datasource;

import io.netty.util.internal.logging.InternalLogger;
import io.netty.util.internal.logging.InternalLoggerFactory;
import org.springframework.orm.jpa.JpaTransactionManager;
import org.springframework.transaction.TransactionDefinition;
import org.springframework.transaction.support.DefaultTransactionStatus;

/**
 * Created by join on 2017/7/3.
 */
public class DsJpaTransactionManager extends JpaTransactionManager {

    private static InternalLogger logger = InternalLoggerFactory.getInstance(DsJpaTransactionManager.class);

    @Override
    protected void doBegin(Object transaction, TransactionDefinition definition) {
        if(definition.isReadOnly()){
            DynamicDataSourceContextHolder.read();
        }else {
            DynamicDataSourceContextHolder.write();
        }
        logger.debug("jpa-transaction:begin-----now dataSource is ["+ DynamicDataSourceContextHolder.getDataSourceType()+"]");

        super.doBegin(transaction, definition);
    }

    @Override
    protected void doCommit(DefaultTransactionStatus status) {
        logger.debug("jpa-transaction:commit-----now dataSource is ["+ DynamicDataSourceContextHolder.getDataSourceType()+"]");
        super.doCommit(status);
    }
}
